const host = import.meta.env.VITE_API_HOST
uni.addInterceptor('request', {
    invoke(args) {
        args.url = host + args.url
    }
})
export function get<T = string>(url: string, data?: object): Promise<MResponse<T>> {
    return buildPromise(
        uni.request({
            url: url,
            dataType: 'json',
            method: 'GET',
            data
        })
    )
}

export function post<T = string>(url: string, data?: object): Promise<MResponse<T>> {
    return buildPromise<T>(
        uni.request({
            url: url,
            dataType: 'json',
            method: 'POST',
            data
        })
    )
}

function buildPromise<T>(src: Promise<UniApp.RequestSuccessCallbackResult>): Promise<MResponse<T>> {
    return src
        .then((res) => {
            let r = res.data as MResponse<T>
            if (r.code == 200) {
                return Promise.resolve(r)
            } else {
                return Promise.reject(r)
            }
        })
        .catch((res) => {
            if (res?.message) {
                uni.showToast({
                    title: res.message,
                    icon: 'none'
                })
            }
            return Promise.reject(res)
        })
}
